/*
 * 客户肤质检测数据详情视图
 * @Author: ljb
 * @Date: 2018-04-23 09:31:20
 * @Last Modified by: ljb
 * @Last Modified time: 2019-05-05 14:08:15
 */
<style lang="less" rel="stylesheet/less" type="text/less">

    .v-customer-skin-test-detail-views {
		height: 100%;
		background: #fff;
		.skin-test-detail {
			height: 100%;
		}
		.userInfo {
			width: 500px;
			// height: 100%;
		}
		.skin-box {
			position: relative;
			padding: 10px 0;
			overflow-y: scroll;
			width: 67%;
			&::-webkit-scrollbar {
				display: none;
			}
			.skin-detail {
				padding-left: 25px;
				overflow: initial;
			}
			/*测肤动向*/
			.skin-test-trend {
				padding-left: 25px;
				overflow: initial;
				margin-top: 30px;
				h4 {
					border-bottom: 1px solid #dddee1;
					span {
						font-size: 18px;
						font-weight: normal;
						display: inline-block;
						color: #666;
						height: 100%;
						padding: 10px 40px;
						margin-right: 18px;
						box-sizing: border-box;
						cursor: pointer;
						text-decoration: none;
						position: relative;
						transition: color .3s ease-in-out;
						border-bottom: 2px solid #E5E5E5;
					}
				}
				.skin_trend {
					margin: 35px 20px;
				}
			}
			/*测肤动向 END*/
			/*选择用户表单*/
			.select-form {
				width: 300px;
			}
			/*选择用户表单 END*/
			/*用户信息区域*/
			.user-info {
				margin-bottom: 20px;
				font-size: 15px;
				border-radius: 20px;
				box-shadow: 0px 0px 10px 2px #ccc;
				.user-img {
					width: 150px;
					height: 150px;
					margin: 10px 0;
					border: 1px solid #ccc;
					border-radius: 50%;
				}
			}
			/*用户信息区域 END*/
			.tab-content {
				/*折线图区域样式*/
				.chart-area {
					/*测肤nav样式*/
					.touch-area,.image-area {
						padding-left: 20px;
						// margin-right: 30px;
					}
					.nav-line {
						display: flex;
						width: 100%;
						.nav-block {
							font-size: 14px;
							width: 20%;
							height: 40px;
							line-height: 40px;
							margin-right: 2px;
							text-align: center;
							background-color: #f0f0f0;
							color: #999;
							cursor: pointer;
							&.selected {
								background-color: #2b85e4;
								color: #fff;
							}
							&.cannot-select {
								background-color: #999;
								cursor: not-allowed;
								color: #666;
							}
						}
					}
					/*测肤nav样式 END*/
				}
				/*折线图区域样式 END*/
				h1 {
					margin: 20px 0;
					font-weight: normal;
				}
				h3 {
					width: 100%;
					font-size: 18px;
					line-height: 70px;
					font-weight: normal;
					box-sizing: border-box;
					white-space: nowrap;
					&.analyse-img {
						// padding-left: 30px;
					}
				}
			}
		}
		.ivu-row-flex{
			flex-wrap: nowrap;
		}
		/*修改选项卡tabs样式*/
		.ivu-tabs-nav-wrap {
			.ivu-tabs-bar {
				margin-bottom: 0;
			}
			.ivu-tabs-tab{
				font-size: 18px;
				color: #999;
				padding: 10px 40px;
			}
			.ivu-tabs-tab-active {
				color: #333333;
			}
		}
		/*修改选项卡tabs样式 END*/
		/*修改测肤动向tabs样式*/
		.skin-trend {
			.ivu-tabs-ink-bar {
				background-color:#E5E5E5;
				height: 3px;
			}
		}
		/*修改测肤动向tabs样式 END*/
		/*暂无测肤数据*/
		.no-data {
			text-align: center;
			transform: translate(0, 80%);
			img {
				width: 315px;
				height: 239px;
			}
			p {
				color: #97CAFF;
				font-size: 30px;
			}
		}
		/*暂无测肤数据 END*/
	}
	/*页码样式*/
	.store-page {
		padding-top: 10px;
	}
	/*页码样式 END*/
	/*model弹窗select样式*/
	.skin-detail-modal {
		.select-form {
			width: 250px;
			padding: 0 20px;
		}
		.ivu-modal-header-inner, .ivu-modal-header p{
			font-size: 18px;
		}
		.ivu-select-selected-value {
			font-size: 14px;
		}
		.ivu-modal-body{
			padding: 15px 0 0 0;
		}
		.ivu-form-item {
			margin-bottom: 10px;
		}
	}
	/*model弹窗select样式 END*/

</style>
<template>
	<div class="v-customer-skin-test-detail-views">
		<Row
			class="skin-test-detail"
			type="flex">

			<div class="userInfo">
				<user-info-card
					:user-info="wechat_user_info"
					:goes-store="goes_store.data"
					:skin-detail-data="skinDetail"
					@show-store="show_store"/>
			</div>

			<div
				:style="{'max-height':formMaxHeight()}"
				class="skin-box">
				<Tabs
					v-model="current_tab"
					class="skin-detail"
					@on-click="changeTab">
					<!-- 智能测肤 -->
					<TabPane
						:label="$t('report_detail.touch_test')"
						class="tab-content"
						name="hm">

						<div v-if="hadRecord">

							<Row
								:gutter="24"
								class="chart-area">
								<i-col
									span="12"
									class="touch-area">
									<h3>{{ $t('report_detail.touch_trend') }}</h3>
									<div class="nav-line">
										<div
											v-for="record in skin_records"
											:key="record.key"
											:class="{'cannot-select' : canNotSelect(record) ,'selected': current_record.key === record.key }"
											class="nav-block"
											@click="selectNav(record)">
											{{ record.value }}
										</div>
									</div>
									<touchLineChart
										:chart-data="currentRecord"
										@show="showTouchDetail"/>
								</i-col>
								<i-col
									span="12"
									class="touch-analyse">
									<h3 class="analyse-img">{{ $t('report_detail.touch_analyse') }}</h3>
									<touchProblem
										:problems="hm_problems"
										:sex="parseInt(skinDetail.sex)"/>
								</i-col>
							</Row>

						</div>

						<!-- 没有测试数据 -->
						<div
							v-else
							class="no-data">
							<img :src="image">
							<p>{{ $t('common.no_test',{'field': people_word[parseInt(skinDetail.sex)] || $t('common.he') }) }}</p>
						</div>

					</TabPane>

					<!-- 3D测肤 -->
					<TabPane
						:label="$t('report_detail.image_test')"
						class="tab-content"
						name="wax">

						<div v-if="hadRecord">
							<Row
								:gutter="24"
								class="chart-area">
								<i-col
									span="11"
									class="image-area">
									<h3>{{ $t('report_detail.image_trend') }}</h3>
									<div class="nav-line">
										<div
											v-for="record in skin_attributes"
											:key="record.key"
											:class="{'cannot-select' : canNotSelect(record) ,'selected': current_record.key === record.key }"
											class="nav-block"
											@click="selectNav(record)">
											{{ record.value }}
										</div>
									</div>
									<imageLineChart
										:chart-data="currentRecord"
										@show="showDetail"/>
								</i-col>
								<i-col
									span="11"
									class="image-analyse">
									<h3 class="analyse-img">{{ $t('report_detail.image_analyse') }}</h3>
									<imageProblem
										:problems="wax_problems"
										:sex="parseInt(skinDetail.sex)"/>
								</i-col>
							</Row>

						</div>

						<!-- 没有测肤数据 -->
						<div
							v-else
							class="no-data">
							<img :src="image">
							<p>{{ $t('common.no_test',{'field': people_word[parseInt(skinDetail.sex)] || $t('common.he') }) }}</p>
						</div>

					</TabPane>
				</Tabs>
				<!-- 测肤动向 -->
				<div
					v-if="hadRecord"
					class="skin-test-trend">
					<h4><span>{{ $t('report_detail.skin_trend') }}</span></h4>
					<div class="skin_trend">
						<skin-test-trend
							:type-id="current_tab"
							:skin-records="current_tab === 'hm' ? hm_data.data : wax_data.data"
							@showModal="showSkinDetail"/>
					</div>

					<!-- 分页组件 -->
					<Row
						type="flex"
						justify="center">
						<Page
							:total="current_tab === 'hm' ? hm_data.total : wax_data.total"
							:current="current_tab === 'hm' ? hm_data.current_page : wax_data.current_page"
							:page-size="query_info.per_page"
							placement="top"
							show-total
							@on-change="pageChange"/>
					</Row>

				</div>
				<!-- 弹出测肤详情 -->
				<Modal
					v-model="show_modal"
					:title="current_tab === 'hm' ? $t('report_detail.touch_test_detail') : $t('report_detail.image_test_detail')"
					class-name="vertical-middle-modal skin-detail-modal"
					width="1200">
					<!-- 下拉选项 -->
					<Form
						ref="formValidate"
						class="select-form">
						<Form-item
							v-if="show_modal"
							prop="name">
							<Select
								v-model="stores_id"
								class="skin-detail-select"
								@on-change="changeSelect">
								<Option
									v-for="user in current_tab === 'hm' ? hm_data.data : wax_data.data"
									:value="Number(user.id)"
									:key="user.id">
									{{ user.store.name + '-' + user.created_at.split(' ')[0] }}
								</Option>
							</Select>
						</Form-item>
					</Form>
					<!-- 测肤详情组件 -->
					<skin-test-detail
						v-if="show_modal"
						:skin-type="current_tab"
						:spin-show="spin_show"
						:detection-parts="skin_records"
						:cause-analysis="skin_detail_data"
						@index="getSkinDetails"/>

					<div slot="footer"/>

				</Modal>
				<!-- 弹出过去店铺 -->
				<Modal
					v-model="stores_list_modal"
					:title="skinDetail.nickname + $t('report_detail.all_stores_list')"
					class-name="vertical-middle-modal"
					width="1200">
					<div
						v-if="stores_list_modal"
						class="user-content">

						<div class="user-index">
							<stores-index
								:loading="table_loading"
								:goes-stores="goes_store.data"/>
						</div>

						<!-- 分页组件 -->
						<Row
							type="flex"
							justify="center"
							class-name="store-page">
							<Page
								:total="goes_store.total"
								:current="goes_store.current_page"
								:page-size="query_info.per_page"
								placement="top"
								show-sizer
								show-total
								@on-change="pageChange"
								@on-page-size-change="perPageChange"/>
						</Row>

					</div>
					<div slot="footer"/>
				</Modal>

			</div>

		</Row>

	</div>
</template>

<script>

import API_LIST from 'src/API_LIST';

import { mapGetters, mapMutations } from 'vuex';

import { computedFormMaxHeight } from 'src/views/mixins/computedFormMaxHeight';

import qs from 'qs';
import touchLineChart from 'src/views/component/touchLineChart';
import imageLineChart from 'src/views/component/imageLineChart';

// 补充
import userInfoCard from 'src/views/component/skin-test/userInfoCard';
import skinTestTrend from 'src/views/component/skin-test/skin-test-trend';
import skinTestDetail from 'src/views/component/skin-test/skin-test-detail';

import imageProblem from 'src/views/component/skin-test/problem-chart/image-problem';
import touchProblem from 'src/views/component/skin-test/problem-chart/touch-problem';

import storesIndex from './stores-index';
// hm的测肤
// const Eye_TAIL = 1;		// 眼尾
// const FACE = 2;			// 脸颊
// const NECK = 3;			// 颈部
// const ARM = 4;			// 手臂

// wax的测肤
// const Sensitivity = 1;		// 皮肤敏感度
// const water = 2;			// 水分测试
// const oil = 3;			// 油脂测试
// const pore = 4;			// 毛孔清洁度
// const Pigment  = 5;			// 色素分解度

export default {
	name: 'SkinTest',
	components: {
		touchLineChart,
		imageLineChart,
		imageProblem,
		touchProblem,
		userInfoCard,
		skinTestTrend,
		skinTestDetail,
		storesIndex,
	},
	mixins: [computedFormMaxHeight],
	props: {
		skinDetail: {
			type: Object,
			default() {
				return {};
			},
		},
	},
	data() {
		return {
			people_word: {
				1: this.$t('common.he'),
				2: this.$t('common.she'),
			},

			image: require('src/assets/img/shuju_wushuju_icon.svg'),

			hm_problems: [],		// 智能测肤的问题

			wax_problems: [],		// 3D测肤的问题

			current_user: '', // 当前查看的用户

			wechat_user_info: {}, // 当前查看的用户信息

			skin_records: [], // 测肤记录

			current_record: [], // 当前选中查看的测肤记录

			true_sort: [3, 2, 1, 5, 4], // wax测试类型nav正确的排序

			skin_attributes: [],		// wax测肤tab

			current_tab: '',		// 当前选中的tab

			query_info: {
				page: 1,

				per_page: 10,

				keyword: '',

				openid: '',

				appid: '',

				customer_id: '',

				skin_detector_id: '',

				testing_start_time: '',

				testing_end_time: '',
			},

			search_info: {
				page: 1,

				per_page: 10,
			}, // 分页信息

			hm_skin: {},	// 智能测肤图表需要的数据

			wax_skin: {},	// 3D测肤图表需要的数据

			table_loading: false,	// 表格的loading

			table_height: 580,

			hm_data: {},	// 智能测肤数据列表

			wax_data: {},	// 3D测肤数据列表

			goes_store: [], // 去过店铺信息

			show_modal: false, // 弹窗的控制

			spin_show: false, // loading控制加载

			stores_id: '', // 选中店铺ID

			tab_index: 0, // 当前选项卡索引值

			skin_detail_data: {}, // 测肤详情信息

			stores_list_modal: false, // 控制过去店铺弹窗

		};
	},
	computed: {

		...mapGetters('spinShow', [
			'getSpin',
		]),

		...mapGetters('userToken', [
			'getUserInfo',
		]),

		...mapGetters('report', [
			'getUserInfos',
		]),

		wechatUserData() {
			return this.wechat_users.data || [];
		},

		currentRecord() {
			const skin_record = this.current_record.skin_records;

			return skin_record || [];
		},

		hadRecord() {
			return this.skin_records.some(record => record.skin_records.length > 0);
		},
	},
	watch: {
		// 监听当前查看的用户的变化
		current_user() {
			const current_info = this.getUserInfos;

			sessionStorage.setItem('watch_user_id', this.current_user);

			this.current_tab = current_info ? current_info.has_data : 'hm';

			this.query_info.openid = current_info.openid;
			this.query_info.appid = current_info.appid;
			this.query_info.customer_id = this.getUserInfo.customer_id;
			this.query_info.skin_detector_id = current_info.skin_detector_id || 3;

			this.fetchSkinData(this.query_info);
			this.fetchGoesStore(this.query_info);
			this.confirmSearch(this.query_info);
		},
	},
	mounted() {
		if (!this.getUserInfos || Object.keys(this.getUserInfos).length === 0) return;
		this.current_user = sessionStorage.getItem('watch_user_id') || this.getUserInfos.id;
	},
	methods: {

		...mapMutations('spinShow', [
			'showSpin',
			'closeSpin',
		]),

		/**
		 * 切换tab
		 * @param  {string} tab_name {tab的name}
         * @return {undefined}
		 */
		changeTab(tab_name) {
			const self = this;

			self.tab_index = 0; // 重置弹窗选项卡索引值

			this.resetSearchParam();

			switch (tab_name) {
			case 'hm':
				self.query_info.skin_detector_id = 3;

				break;
			case 'wax':

				self.query_info.skin_detector_id = 2;
				break;
			default:
				break;
			}

			this.fetchSkinData(this.query_info);
			this.confirmSearch(this.query_info);
		},

		/**
		 * 展示hm测肤当天详情信息
		 * @param  {string} time {当天时间}
		 * @return {undefined}
		 */
		showTouchDetail(time) {
			if (!time) return;

			const real_skin_record = this.currentRecord.filter(skin_record => skin_record.created_at === time)[0];

			const problems = [];

			const records = this.skin_records;

			if (!records || records.length === 0) return;

			records.forEach((record) => {
				record.skin_records.forEach((skin_record) => {
					if (skin_record.skin_record_id === real_skin_record.skin_record_id) {
						const param = {
							position: skin_record.position,
							values: skin_record.labels ? [...skin_record.labels] : [],
						};

						problems.push(param);
					}
				});
			});
			this.hm_problems = problems;
		},

		/**
		 * 展示wax测肤当天详情信息
		 * @param  {string} time {当天时间}
		 * @return {undefined}
		 */
		showDetail(time) {
			if (!time) return;
			const real_skin_record = this.currentRecord.filter(skin_record => skin_record.created_at === time)[0];

			const problems = [];

			const records = this.skin_attributes;

			if (!records || records.length === 0) return;

			records.forEach((record) => {
				record.skin_records.forEach((skin_record) => {
					if (skin_record.skin_record_id === real_skin_record.skin_record_id) {
						const param = {
							itemsid: skin_record.itemsid,
							problem: skin_record.levelname,
						};
						problems.push(param);
					}
				});
			});
			this.wax_problems = problems;
		},

		/**
         * 初始化皮肤属性的nav，并且排序好
         * @return {undefined}
         */
		initSkinAttri() {
			const new_array = [];

			this.true_sort.forEach((sort) => {
				this.skin_records.forEach((record) => {
					if (parseInt(record.key, 10) === sort) {
						new_array.push(record);
					}
				});
			});

			this.skin_attributes = new_array;

			this.autoSelectUseValue(this.skin_attributes);
		},

		/**
         * 判断nav是否不可选
         * @param  {Object} record {当前需要判断的nav}
         * @return {Boolean} {true代表不可选，false可选}
         */
		canNotSelect(record) {
			return record.skin_records.length === 0;
		},

		/**
         * 选中智能测肤的nav
         * @param  {Object} record {当前选中查看的测肤部位对象}
         * @return {undefined}
         */
		selectNav(record) {
			if (!record.skin_records || record.skin_records.length === 0) return;
			this.current_record = record;
		},

		/**
         * 自动选中第一个可选的值
         * @return {undefined}
         */
		autoSelectUseValue(records) {
			const self = this;

			for (let i = 0; i < records.length; i += 1) {
				const record = records[i];

				if (record.skin_records && record.skin_records.length > 0) {
					self.current_record = record;

					return;
				}
			}
		},

		/**
		 * 重置搜索参数
		 * @return {undefined}
		 */
		resetSearchParam() {
			this.query_info.page = 1;
			this.query_info.per_page = 10;
			this.query_info.testing_start_time = '';
			this.query_info.testing_end_time = '';
			this.query_info.keyword = '';

			this.search_info = {
				page: 1,

				per_page: 10,
			};
		},

		/**
         * 页码改变
         * @param  {string} pageNumber {当前页码}
         * @return {undefined}
         */
		pageChange(pageNumber) {
			this.search_info.page = pageNumber;

			this.search_info.per_page = this.query_info.per_page;

			this.fetchDataList(this.search_info);
		},

		/**
         * 每页显示数改变
         * @param  {string} per_page {当前每页显示数}
         * @return {undefined}
         */
		perPageChange(per_page) {
			this.search_info.per_page = per_page;

			this.query_info.per_page = per_page;

			this.fetchDataList(this.query_info);
		},

		/**
		* 确认搜索
		* @param  {string}  keyword {关键字}
		* @param  {Number}  skin_detector_id {需要查看的肤质检测类型}
		* @param  {Array}  born_dates {出生日期区间}
		* @return {undefined}
		*/
		confirmSearch({
			keyword, time_ranges,
		}) {
			this.query_info.keyword = keyword || '';

			[this.query_info.testing_start_time, this.query_info.testing_end_time] = time_ranges || [];

			this.search_info = JSON.parse(JSON.stringify(this.query_info));

			this.fetchDataList(this.query_info);
		},

		/**
		 * 肤质检测数据列表
		 * @param {Object} param {列表参数}
		 * @return {undefined}
		 */
		fetchDataList(param) {
			this.showSpin(this.$t('common.please_wait'));

			const query_str = qs.stringify(param);

			this.$http.get(`${API_LIST.CUST_SKIN_DATA_LIST}?${query_str}`)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					const key = `${this.current_tab}_data`;

					this[key] = data.skin_records;
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(this.closeSpin);
		},

		/**
         * 获取用户的肤质数据列表
		 * @param {Object} param {搜索参数}
         * @return {undefined}
         */
		fetchSkinData({
			openid, appid, skin_detector_id, customer_id,
		}) {
			if (this.getSpin) return;

			const param = {
				openid,
				appid,
				skin_detector_id,
				customer_id,
			};

			this.showSpin(this.$t('common.please_wait'));

			const query_str = qs.stringify(param);

			this.$http.get(`${API_LIST.CUST_SKIN_DETAIL}?${query_str}`)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.wechat_user_info = data.wechat_user_info;

					this.skin_records = data.skin_records;

					if (this.current_tab === 'wax') {
						this.initSkinAttri();
					} else {
						this.autoSelectUseValue(this.skin_records);
					}
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(this.closeSpin);
		},
		/**
		 * 获取过去店铺信息
		 * @param {Object} openid {微信用户的openid}
		 * @return {undefined} {description}
		 */
		fetchGoesStore({ openid }) {
			this.table_loading = true;

			const param = { openid };
			const query_str = qs.stringify(param);
			this.$http.get(`${API_LIST.CUST_GROUP_BY_STORES}?${query_str}`)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.goes_store = data.stores;
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(() => { this.table_loading = false; });
		},

		/**
		 * 显示过去店铺弹窗
		 * @return {undefined} {description}
		 */
		show_store() {
			this.stores_list_modal = true;
		},

		/**
		 * 下拉选择切换测肤详情数据
		 * @param {String} value {选中的value值}
		 * @return {type} {description}
		 */
		changeSelect(value) {
			this.showLoading();
			this.processData(value, this.tab_index);
		},

		/**
		 * 显示弹窗
		 * @param {Number} id {匹配select选中值}
		 * @return {undefined} {description}
		 */
		showSkinDetail(id) {
			this.show_modal = true;
			this.stores_id = id;
			this.showLoading();
			if (this.current_tab === 'hm') {
				this.processData(id, 1);
				this.tab_index = 1;
			} else {
				this.processData(id, 3);
				this.tab_index = 3;
			}
		},

		/**
		 * 控制loading动画显/隐
		 * @return {undefined} {description}
		 */
		showLoading() {
			this.spin_show = true;
			setTimeout(() => {
				this.spin_show = false;
			}, 800);
		},

		/**
		 * 切换不同部位获取相应数据
		 * @param {Number} index {index索引值}
		 * @return {type} {description}
		 */
		getSkinDetails(index) {
			this.showLoading();
			this.tab_index = index;
			this.processData(this.stores_id, index);
		},

		/**
		 * 测肤详情数据处理
		 * @param  {Object} data  {肤质详情数据}
		 * @param  {undefined}
		 */
		processData(id, num) {
			if (this.current_tab === 'hm') {
				const [hm_fetchData] = this.hm_data.data.filter(item => item.id === id);
				const [hm_skin_records] = hm_fetchData.hm_skin_records.filter(item => item.position === num);
				this.skin_detail_data = hm_skin_records;
			} else {
				const [wa_fetchData] = this.wax_data.data.filter(item => item.id === id);

				const [wax_skin_records] = wa_fetchData.wax_skin_records.filter(item => item.itemsid === num);

				this.skin_detail_data = wax_skin_records;
			}
		},

	},
};
</script>
